package xing.test.voice.rtp.redfire;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioFileFormat;

import java.io.File;
import java.io.FileInputStream;

public class AudioSenderXing {
	/** The main method. */
	public static void main(String[] args) {
		String daddr = "10.10.9.104";
		int dport = 10000;
		int frame_size = 500;
		int frame_rate; // =sample_rate/(frame_size/sample_size);
		// byte_rate=frame_rate/frame_size=8000
		boolean linear_signed = false;
		boolean pcmu = false;
		boolean big_endian = false;
		String filename = null;
		boolean sound = true;

		boolean help = true;

		if (help) {
			System.out
					.println("usage:\n  java AudioSender <dest_addr> <dest_port> [options]");
			System.out.println("   options:");
			System.out.println("   -h               this help");
			System.out.println("   -p <type>        payload type");
			System.out.println("   -F <audio_file>  sends an audio file");
			System.out
					.println("   -T <frequency>   sends a tone of given frequency [Hz]");
			System.out
					.println("   -A <amplitude>   sets an amplitude factor [0:1]");
			System.out
					.println("   -S <rate> <size> sample rate [B/s], and size [B]");
			System.out.println("   -L <size>        frame size");
			System.out
					.println("   -Z               uses PCM linear signed format (linear unsigned is used as default)");
			System.out.println("   -U               uses PCMU format");
			System.out.println("   -E               uses big endian format");
		}

		try {
			RtpStreamSender sender = null;
			AudioInput audio_input = null;

			if (sound)
				AudioInput.initAudioLine();

			if (sound) {
				// Open Declaration javax.sound.sampled.AudioFormat
				// AudioFormat format = new AudioFormat(codec, sample_rate,
				// 8 * sample_size, 1, sample_size, sample_rate,
				// big_endian);
				// AudioFormat format = new AudioFormat(8000, 16, 2, true,
				// true);
				AudioFormat.Encoding encoding = AudioFormat.Encoding.PCM_UNSIGNED;
				int rate = 8000;
				int sampleSize = 8;
				boolean bigEndian = true;
				int channels = 1;
				AudioFormat format = new AudioFormat(encoding, rate,
						sampleSize, channels, (sampleSize / 8) * channels,
						rate, bigEndian);

				frame_rate = rate / (frame_size / sampleSize);
				System.out.println("System audio format: " + format);
				audio_input = new AudioInput(format);
				sender = new RtpStreamSender(audio_input.getInputStream(),
						false, 0, frame_rate, frame_size, daddr, dport);
			}
			if (sender != null) {
				sender.start();
				if (sound)
					audio_input.play();

				System.out.println("Press 'Return' to stop");
				System.in.read();

				sender.halt();
				if (sound)
					audio_input.stop();
				if (sound)
					AudioInput.closeAudioLine();
			} else {
				System.out.println("Error creating the rtp stream.");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
